<template>
  <div class="warehouse-container">
    <div class="header">
      <h2>半成品储位划分</h2>
      <button
        class="confirm-btn"
        :disabled="isSubmitting"
        @click="submitZones"
      >
        <i class="fas fa-check" /> {{ isSubmitting ? '提交中...' : '确认划分' }}
      </button>
    </div>

    <div v-if="loading" class="loading">
      <div class="spinner" />
      <p>加载储位数据中...</p>
    </div>

    <div v-else-if="error" class="error-message">
      <i class="fas fa-exclamation-circle" /> {{ error }}
    </div>

    <div v-else class="zone-editor">
      <!-- 储位标尺容器 -->
      <div class="ruler-container">
        <!-- 储位标尺 -->
        <div class="ruler">
          <div class="ruler-line" />
          <div
            v-for="mark in rulerMarks"
            :key="mark"
            :style="{ left: `${(mark / totalPositions) * 100}%` }"
            class="ruler-mark"
          >
            <span class="mark-tick" />
            <span class="mark-label">{{ mark }}</span>
          </div>

          <!-- 50倍数位置的高亮标记 -->
          <div
            v-for="step in fiftySteps"
            :key="step"
            :style="{ left: `${(step / totalPositions) * 100}%` }"
            class="fifty-marker"
          />
        </div>
      </div>

      <!-- 库区展示和编辑区域 -->
      <div class="zones-container">
        <div
          v-for="(zone, index) in zones"
          :key="index"
          :style="{
            left: `${(zone.start / totalPositions) * 100}%`,
            width: `${((zone.end - zone.start) / totalPositions) * 100}%`,
            background: zone.gradient,
            borderColor: zone.borderColor
          }"
          class="zone"
          :class="{
            'zone-selected': draggingZoneIndex === index,
            'zone-dragging': isDraggingZone,
            'zone-hover': !isDraggingZone && !isDragging && draggingZoneIndex === -1
          }"
          @mousedown="startDragZone(index, $event)"
          @touchstart="startDragZone(index, $event, true)"
        >
          <div class="zone-info">
            <strong>{{ zone.name }}</strong>
            <span>{{ zone.start }}-{{ zone.end }}</span>
            <span class="zone-size">尺寸: {{ zone.end - zone.start }}</span>
          </div>
        </div>

        <!-- 拖拽分隔线 -->
        <div
          v-for="(divider, index) in dividers"
          :key="index"
          :style="{ left: `${(divider.position / totalPositions) * 100}%` }"
          class="divider"
          :class="{
            dragging: divider.isDragging,
            'near-marker': divider.nearMarker,
            'at-marker': divider.atMarker
          }"
          @mousedown="startDrag(index, $event)"
          @touchstart="startDrag(index, $event, true)"
        >
          <div class="divider-handle" />
        </div>

        <!-- 拖拽指示器 -->
        <div
          v-if="showDropIndicator"
          class="drop-indicator"
          :style="{ left: `${dropIndicatorPosition}%` }"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 状态管理
      loading: true,
      error: '',
      isSubmitting: false,

      // 储位数据
      totalPositions: 0,
      zones: [],
      dividers: [],

      // 分隔线拖拽状态
      isDragging: false,
      currentDivider: -1,
      isDraggingActive: false,

      // 库区拖拽状态
      isDraggingZone: false,
      draggingZoneIndex: -1,
      originalZoneIndex: -1,
      showDropIndicator: false,
      dropIndicatorPosition: 0,

      // 标尺刻度间隔
      rulerInterval: 100,

      // 磁吸间隔
      magneticInterval: 50,
      magneticRange: 10
    }
  },

  computed: {
    // 生成标尺刻度
    rulerMarks() {
      const marks = []
      for (let i = 0; i <= this.totalPositions; i += this.rulerInterval) {
        marks.push(i)
      }
      // 确保最后一个刻度是总储位数
      if (marks[marks.length - 1] !== this.totalPositions) {
        marks.push(this.totalPositions)
      }
      return marks
    },

    // 生成50倍数的位置标记
    fiftySteps() {
      const steps = []
      for (let i = this.magneticInterval; i < this.totalPositions; i += this.magneticInterval) {
        steps.push(i)
      }
      return steps
    }
  },

  mounted() {
    // 页面加载时使用假数据初始化
    this.initFakeData()

    // 添加鼠标和触摸事件监听
    window.addEventListener('mousemove', this.handleDrag)
    window.addEventListener('mouseup', this.endDrag)
    window.addEventListener('touchmove', this.handleDrag, { passive: false })
    window.addEventListener('touchend', this.endDrag)
  },

  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('mousemove', this.handleDrag)
    window.removeEventListener('mouseup', this.endDrag)
    window.removeEventListener('touchmove', this.handleDrag)
    window.removeEventListener('touchend', this.endDrag)
  },

  methods: {
    // 使用假数据初始化
    initFakeData() {
      try {
        // 模拟从后端获取的数据
        const fakeData = {
          totalPositions: 1000, // 总储位数为1000
          zones: [
            { name: '库区1', start: 0, end: 100 },
            { name: '库区2', start: 100, end: 400 },
            { name: '库区3', start: 400, end: 700 },
            { name: '库区4', start: 700, end: 1000 }
          ]
        }

        this.totalPositions = fakeData.totalPositions
        this.zones = fakeData.zones.map(zone => ({
          ...zone,
          // 为每个库区分配不同的渐变和边框色
          gradient: this.getZoneGradient(fakeData.zones.indexOf(zone)),
          borderColor: this.getZoneBorderColor(fakeData.zones.indexOf(zone))
        }))

        // 生成分隔线
        this.updateDividers()

        this.loading = false
      } catch (err) {
        this.error = '获取储位数据失败，请重试'
        this.loading = false
        console.error('Failed to initialize fake data:', err)
      }
    },

    // 更新分隔线位置
    updateDividers() {
      this.dividers = []
      // 除了最后一个区域，每个区域结束位置都有一个分隔线
      for (let i = 0; i < this.zones.length - 1; i++) {
        this.dividers.push({
          position: this.zones[i].end,
          isDragging: false,
          nearMarker: false,
          atMarker: false
        })
      }
    },

    // 获取库区的渐变背景
    getZoneGradient(index) {
      // 柔和、专业的渐变配色
      const gradients = [
        'linear-gradient(135deg, rgba(66, 153, 225, 0.85) 0%, rgba(52, 144, 220, 0.75) 100%)', // 专业蓝
        'linear-gradient(135deg, rgba(72, 187, 120, 0.85) 0%, rgba(52, 168, 83, 0.75) 100%)', // 清新绿
        'linear-gradient(135deg, rgba(100, 116, 139, 0.85) 0%, rgba(75, 85, 99, 0.75) 100%)', // 商务灰蓝
        'linear-gradient(135deg, rgba(96, 165, 250, 0.85) 0%, rgba(59, 130, 246, 0.75) 100%)', // 浅靛蓝
        'linear-gradient(135deg, rgba(165, 180, 252, 0.85) 0%, rgba(124, 58, 237, 0.75) 100%)', // 柔和紫
        'linear-gradient(135deg, rgba(6, 182, 212, 0.85) 0%, rgba(5, 150, 105, 0.75) 100%)' // 青绿过渡
      ]
      return gradients[index % gradients.length]
    },

    // 获取库区的边框颜色
    getZoneBorderColor(index) {
      // 对应渐变的深色版本作为边框
      const borderColors = [
        'rgba(45, 126, 203, 0.9)', // 专业蓝边框
        'rgba(43, 135, 97, 0.9)', // 清新绿边框
        'rgba(63, 78, 94, 0.9)', // 商务灰蓝边框
        'rgba(49, 112, 206, 0.9)', // 浅靛蓝边框
        'rgba(99, 46, 199, 0.9)', // 柔和紫边框
        'rgba(5, 140, 98, 0.9)' // 青绿过渡边框
      ]
      return borderColors[index % borderColors.length]
    },

    // 开始拖拽分隔线
    startDrag(index, event, isTouch = false) {
      // 如果正在拖拽库区，则忽略分隔线拖拽
      if (this.isDraggingZone) return

      event.preventDefault()
      this.isDragging = true
      this.isDraggingActive = true
      this.currentDivider = index
      this.dividers[index].isDragging = true

      // 添加样式类优化性能
      document.body.classList.add('dragging-in-progress')
    },

    // 开始拖拽库区
    startDragZone(index, event, isTouch = false) {
      // 如果正在拖拽分隔线，则忽略库区拖拽
      if (this.isDragging) return

      event.preventDefault()
      this.isDraggingZone = true
      this.draggingZoneIndex = index
      this.originalZoneIndex = index

      // 添加样式类优化性能
      document.body.classList.add('dragging-in-progress')
    },

    // 处理拖拽
    handleDrag(event) {
      if (this.isDragging && this.currentDivider !== -1) {
        this.handleDividerDrag(event)
      } else if (this.isDraggingZone && this.draggingZoneIndex !== -1) {
        this.handleZoneDrag(event)
      }
    },

    // 处理分隔线拖拽
    handleDividerDrag(event) {
      // 限制拖拽频率，提升性能
      if (!this.isDraggingActive) {
        requestAnimationFrame(() => {
          this.isDraggingActive = true
          this.performDividerDrag(event)
        })
        this.isDraggingActive = false
        return
      }

      this.performDividerDrag(event)
    },

    // 实际执行分隔线拖拽计算，包含磁吸功能
    performDividerDrag(event) {
      // 获取鼠标或触摸位置
      const clientX = event.type.includes('mouse')
        ? event.clientX
        : event.touches[0].clientX

      // 获取容器位置和宽度
      const container = this.$el.querySelector('.zones-container')
      const rect = container.getBoundingClientRect()
      const containerWidth = rect.width

      // 计算相对位置（0到总储位数之间）
      let relativeX = (clientX - rect.left) / containerWidth
      relativeX = Math.max(0, Math.min(1, relativeX)) // 限制在0-1之间
      let newPosition = Math.round(relativeX * this.totalPositions)

      // 磁吸逻辑：检查是否接近50的倍数
      const nearestMarker = this.getNearestFiftyMarker(newPosition)
      const isNearMarker = nearestMarker.distance <= this.magneticRange

      // 如果在磁吸范围内，吸附到最近的标记点
      if (isNearMarker) {
        newPosition = nearestMarker.position
      }

      // 更新分隔线的磁吸状态
      this.dividers[this.currentDivider].nearMarker = isNearMarker
      this.dividers[this.currentDivider].atMarker = isNearMarker

      // 确保位置合理（不小于前一个分隔线，不大于后一个分隔线）
      const prevDividerPos = this.currentDivider > 0
        ? this.dividers[this.currentDivider - 1].position
        : 0

      const nextDividerPos = this.currentDivider < this.dividers.length - 1
        ? this.dividers[this.currentDivider + 1].position
        : this.totalPositions

      newPosition = Math.max(prevDividerPos + 1, Math.min(nextDividerPos - 1, newPosition))

      // 更新分隔线位置
      this.dividers[this.currentDivider].position = newPosition

      // 更新库区范围
      this.updateZonesFromDividers()
    },

    // 处理库区拖拽
    handleZoneDrag(event) {
      event.preventDefault()

      // 获取鼠标或触摸位置
      const clientX = event.type.includes('mouse')
        ? event.clientX
        : event.touches[0].clientX

      // 获取容器位置和宽度
      const container = this.$el.querySelector('.zones-container')
      const rect = container.getBoundingClientRect()
      const containerWidth = rect.width

      // 计算相对位置百分比
      const relativeX = (clientX - rect.left) / containerWidth
      const relativePercent = Math.max(0, Math.min(100, relativeX * 100))

      // 显示放置指示器并更新位置
      this.showDropIndicator = true
      this.dropIndicatorPosition = relativePercent

      // 确定新位置
      this.calculateNewZonePosition(relativeX)
    },

    // 计算库区的新位置
    calculateNewZonePosition(relativeX) {
      const absoluteX = relativeX * this.totalPositions

      // 找到应该插入的位置
      let newIndex = 0
      for (let i = 0; i < this.zones.length; i++) {
        // 跳过正在拖拽的库区
        if (i === this.draggingZoneIndex) continue

        // 计算当前库区的中点
        const zoneMidpoint = (this.zones[i].start + this.zones[i].end) / 2

        // 如果拖拽位置超过当前库区中点，则考虑下一个位置
        if (absoluteX > zoneMidpoint) {
          newIndex = i + 1
        } else {
          break
        }
      }

      // 确保不会超出范围
      newIndex = Math.max(0, Math.min(this.zones.length - 1, newIndex))

      // 如果位置有变化，更新拖拽索引
      if (newIndex !== this.draggingZoneIndex) {
        this.draggingZoneIndex = newIndex
      }
    },

    // 结束拖拽
    endDrag() {
      if (this.isDragging && this.currentDivider !== -1) {
        // 结束分隔线拖拽
        this.dividers[this.currentDivider].isDragging = false
        this.dividers[this.currentDivider].nearMarker = false
        this.isDragging = false
        this.isDraggingActive = false
        this.currentDivider = -1
      } else if (this.isDraggingZone && this.draggingZoneIndex !== -1) {
        // 结束库区拖拽，应用新位置
        if (this.draggingZoneIndex !== this.originalZoneIndex) {
          this.moveZoneToNewPosition(this.originalZoneIndex, this.draggingZoneIndex)
        }

        this.isDraggingZone = false
        this.draggingZoneIndex = -1
        this.originalZoneIndex = -1
        this.showDropIndicator = false
      }

      // 移除性能优化样式类
      document.body.classList.remove('dragging-in-progress')
    },

    // 将库区移动到新位置，同时保持原有大小
    moveZoneToNewPosition(oldIndex, newIndex) {
      // 保存被移动的库区及其大小
      const movedZone = this.zones[oldIndex]
      // const movedZoneSize = movedZone.end - movedZone.start

      // 创建新数组并移动库区
      const newZones = [...this.zones]
      newZones.splice(oldIndex, 1)
      newZones.splice(newIndex, 0, movedZone)

      // 计算所有库区的新位置，保持各自的大小
      let currentPosition = 0
      const updatedZones = newZones.map(zone => {
        // 计算当前库区的大小
        const zoneSize = zone.end - zone.start
        const updated = {
          ...zone,
          start: currentPosition,
          end: currentPosition + zoneSize
        }
        currentPosition = updated.end
        return updated
      })

      // 确保最后一个库区的结束位置是总储位数
      if (updatedZones.length > 0) {
        const lastIndex = updatedZones.length - 1
        updatedZones[lastIndex].end = this.totalPositions
      }

      // 更新数据
      this.zones = updatedZones
      this.updateDividers()
    },

    // 找到最近的50倍数标记
    getNearestFiftyMarker(position) {
      // 计算距离最近的50倍数
      const remainder = position % this.magneticInterval
      const lower = position - remainder
      const upper = remainder === 0 ? lower : lower + this.magneticInterval

      // 确定哪个更近
      const distanceToLower = position - lower
      const distanceToUpper = upper - position

      if (distanceToLower < distanceToUpper) {
        return { position: lower, distance: distanceToLower }
      } else {
        return { position: upper, distance: distanceToUpper }
      }
    },

    // 根据分隔线位置更新库区范围
    updateZonesFromDividers() {
      let lastPosition = 0

      // 更新现有区域
      this.zones.forEach((zone, index) => {
        zone.start = lastPosition
        if (index < this.dividers.length) {
          zone.end = this.dividers[index].position
          lastPosition = this.dividers[index].position
        } else {
          // 最后一个区域
          zone.end = this.totalPositions
        }
      })
    },

    // 提交新的库区划分
    async submitZones() {
      try {
        this.isSubmitting = true

        // 准备提交的数据
        const submitData = {
          totalPositions: this.totalPositions,
          zones: this.zones.map(zone => ({
            name: zone.name,
            start: zone.start,
            end: zone.end
          }))
        }

        // 模拟API请求
        console.log('提交库区划分数据:', submitData)

        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 800))

        // 模拟成功提示
        alert('库区划分已成功更新')
        this.isSubmitting = false
      } catch (err) {
        alert('提交失败，请重试')
        this.isSubmitting = false
        console.error('Failed to submit zones:', err)
      }
    }
  }
}
</script>

<style scoped>
.warehouse-container {
  margin: 20px auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.header h2 {
  margin: 0;
  color: #333;
  font-size: 1.5rem;
  font-weight: 600;
}

.confirm-btn {
  background-color: #4299e1;
  color: white;
  border: none;
  padding: 9px 18px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.confirm-btn:hover:not(:disabled) {
  background-color: #3182ce;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(66, 153, 225, 0.3);
}

.confirm-btn:disabled {
  background-color: #e9ecef;
  color: #adb5bd;
  cursor: not-allowed;
}

.loading {
  text-align: center;
  padding: 60px 20px;
  background-color: #f8fafc;
  border-radius: 8px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid #f1f5f9;
  border-top: 4px solid #4299e1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  color: #e53e3e;
  padding: 15px 20px;
  text-align: center;
  background-color: #fff5f5;
  border-radius: 6px;
  border-left: 4px solid #e53e3e;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.zone-editor {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 20px;
  background-color: #f8fafc;
}

.ruler-container {
  margin-bottom: 25px;
  position: relative;
  height: 50px;
}

.ruler {
  position: relative;
  height: 100%;
  width: 100%;
}

.ruler-line {
  position: absolute;
  bottom: 20px;
  width: 100%;
  height: 2px;
  background-color: #cbd5e1;
  z-index: 1;
}

.ruler-mark {
  position: absolute;
  bottom: 0;
  height: 100%;
  transform: translateX(-50%);
  z-index: 2;
}

.mark-tick {
  position: absolute;
  bottom: 20px;
  width: 1px;
  height: 12px;
  background-color: #94a3b8;
}

.mark-label {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  font-size: 13px;
  color: #64748b;
  font-weight: 500;
  white-space: nowrap;
  padding: 3px 6px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 3px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 50倍数位置的标记 */
.fifty-marker {
  position: absolute;
  bottom: 15px;
  width: 2px;
  height: 20px;
  background-color: #3182ce;
  transform: translateX(-50%);
  z-index: 3;
  opacity: 0.6;
}

.zones-container {
  position: relative;
  height: 180px;
  border: 1px solid #e2e8f0;
  background-color: white;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.02);
}

.zone {
  position: absolute;
  height: 100%;
  border-right: 1px solid;
  box-sizing: border-box;
  transition: width 0.08s ease-out, left 0.08s ease-out;
  box-shadow: 1px 0 3px rgba(0, 0, 0, 0.05);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  cursor: move;
  user-select: none;
}

.zone:last-child {
  border-right: none;
}

.zone-hover {
  filter: brightness(1.05);
}

.zone-selected {
  filter: brightness(1.1);
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.8), 0 0 15px rgba(0, 0, 0, 0.1);
  z-index: 15;
}

.zone-dragging {
  opacity: 0.9;
  transform: scale(1.02);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
  z-index: 30;
}

.zone-info {
  padding: 15px;
  color: #ffffff;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.zone-info span {
  display: block;
  font-weight: normal;
  font-size: 13px;
  margin-top: 5px;
}

.zone-size {
  font-size: 12px;
  opacity: 0.9;
  margin-top: 3px;
}

.divider {
  position: absolute;
  top: 0;
  height: 100%;
  width: 2px;
  background-color: rgba(255, 255, 255, 0.7);
  transform: translateX(-1px);
  cursor: col-resize;
  z-index: 10;
  transition: background-color 0.2s, width 0.2s, transform 0.2s;
}

.divider:hover {
  background-color: rgba(255, 255, 255, 0.9);
  width: 4px;
  transform: translateX(-2px);
}

.divider.dragging {
  background-color: #ffffff;
  width: 4px;
  transform: translateX(-2px);
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.5);
  z-index: 20;
}

/* 接近磁吸点时的样式 */
.divider.near-marker {
  background-color: #3182ce;
  box-shadow: 0 0 0 3px rgba(49, 130, 206, 0.3);
}

/* 吸附到磁吸点时的样式 */
.divider.at-marker {
  background-color: #2254b6;
  box-shadow: 0 0 0 4px rgba(34, 84, 182, 0.4);
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(34, 84, 182, 0.4);
  }
  70% {
    box-shadow: 0 0 0 8px rgba(34, 84, 182, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(34, 84, 182, 0);
  }
}

.divider-handle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #fff;
  border: 2px solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.divider.dragging .divider-handle {
  box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.6);
  transform: translate(-50%, -50%) scale(1.2);
}

.divider.near-marker .divider-handle,
.divider.at-marker .divider-handle {
  background-color: #3182ce;
  border-color: #3182ce;
}

/* 拖拽指示器样式 */
.drop-indicator {
  position: absolute;
  top: 0;
  height: 100%;
  width: 4px;
  background-color: #e53e3e;
  transform: translateX(-2px);
  z-index: 25;
  box-shadow: 0 0 0 2px rgba(229, 62, 62, 0.3);
  animation: indicatorPulse 1.5s infinite;
}

@keyframes indicatorPulse {
  0% {
    box-shadow: 0 0 0 0 rgba(229, 62, 62, 0.5);
  }
  70% {
    box-shadow: 0 0 0 8px rgba(229, 62, 62, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(229, 62, 62, 0);
  }
}

/* 优化拖拽性能 */
.dragging-in-progress .zone {
  transition: none !important;
  will-change: width, left;
}
</style>
